<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>示例9</title>
    <script>
        class Person {
            #age; // 定义私有属性,外部无法直接访问 
            constructor(age) {
                this.age = age;
            }
            // age 属性的 setter 
            set age(value) {
                // setter 方法可以对传入的参数进行校验 
                if (value < 0 || value > 100) {
                    // 或者抛出异常：throw 'age must between 1 and 100' 
                    console.log("setter error, age must between 1 and 100");
                    return;
                }
                this.#age = value;
            }
            // age 属性的 getter 
            get age() {
                return this.#age;
            }
        }
        let person = new Person(20);
        person.age = 101; // age 属性被 setter 方法拦截，不合理的值被拒绝 
        console.log(person.age); // 20 
    </script>
</head>
<body></body>
</html>